<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true" :label-width="100">
            <el-form-item label="创建时间" prop="queryCreateTime">
              <el-select v-model="queryParams.queryCreateTime" placeholder="请选择创建时间">
                <el-option label="近一天" :value="1" />
                <el-option label="近三天" :value="3" />
                <el-option label="近七天" :value="7" />
                <el-option label="近一月" :value="30" />
                <el-option label="近三月" :value="90" />
                <el-option label="近半年" :value="180" />
                <el-option label="近一年" :value="365" />
                <el-option label="全部" :value="-1" />
              </el-select>
            </el-form-item>
            <el-form-item label="优惠券名称" prop="discountsName">
              <el-input v-model="queryParams.discountsName" placeholder="请输入优惠券名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
<!--            <el-form-item label="领取时间" prop="discountsGetStartTime">-->
<!--              <el-date-picker-->
<!--                v-model="queryParams.discountsGetTimeList"-->
<!--                type="daterange"-->
<!--                range-separator="至"-->
<!--                start-placeholder="领取开始时间"-->
<!--                end-placeholder="领取结束时间"-->
<!--                value-format="YYYY-MM-DD HH:mm:ss"-->
<!--                :default-time="[new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 1, 1, 23, 59, 59)]"-->
<!--              />-->
<!--            </el-form-item>-->
            <el-form-item label="是否作废" prop="isDisabled">
              <el-select v-model="queryParams.isDisabled" placeholder="请选择是否作废" clearable>
                <el-option v-for="dict in sys_yes_no" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="是否限领" prop="getLimitType">
              <el-select v-model="queryParams.getLimitType" placeholder="请选择是否限领" clearable>
                <el-option v-for="dict in sys_yes_no" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="店铺展示" prop="isShopShow">
              <el-select v-model="queryParams.isShopShow" placeholder="请选择店铺是否展示" clearable>
                <el-option v-for="dict in sys_yes_no" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="领券中心展示" prop="isGetCentreShow">
              <el-select v-model="queryParams.isGetCentreShow" placeholder="请选择领券中心是否展示" clearable>
                <el-option v-for="dict in sys_yes_no" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="券码类型" prop="discountsCdkType">
              <el-select v-model="queryParams.discountsCdkType" placeholder="请选择领券码类型" clearable>
                <el-option v-for="dict in discounts_cdk_type" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button v-hasPermi="['shop:discountsInfo:add']" type="primary" plain icon="Plus" @click="handleAdd">新增</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @query-table="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" border :data="discountsInfoList">
        <el-table-column label="基础信息" align="center">
          <template #default="scope">
            <el-row>
              <el-col :span="10"> 名称： </el-col>
              <el-col :span="14">
                {{ scope.row.discountsName }}
              </el-col>
            </el-row>
            <el-row style="margin-top: 10px">
              <el-col :span="10"> 编码： </el-col>
              <el-col :span="14">
                {{ scope.row.discountsCode }}
              </el-col>
            </el-row>
            <el-row style="margin-top: 10px">
              <el-col :span="10"> 范围： </el-col>
              <el-col :span="14">
                <dict-tag :options="goods_scope_type" :value="scope.row.goodsScopeType" />
              </el-col>
            </el-row>
            <el-card v-if="scope.row.cardCollageVo" style="margin-top: 10px" align="left">
              <div>
                <el-link type="primary">拼团名称：{{ scope.row.cardCollageVo.collageName }}</el-link>
              </div>
              <div style="margin-top: 5px">
                <el-link type="danger">拼团编码：{{ scope.row.cardCollageVo.collageCode }}</el-link>
              </div>
            </el-card>
          </template>
        </el-table-column>
        <el-table-column label="优惠信息" align="center">
          <template #default="scope">
            <el-row>
              <el-col :span="10"> 类型： </el-col>
              <el-col :span="14">
                <dict-tag :options="discounts_type" :value="scope.row.discountsType" />
              </el-col>
            </el-row>
            <el-row style="margin-top: 10px">
              <el-col :span="10"> 金额： </el-col>
              <el-col :span="14">
                <span v-if="scope.row.discountsType == '1'" style="color: dodgerblue"
                  >满 {{ scope.row.fullUseMoney }} 元优惠 {{ scope.row.subtractMoney }} 元</span
                >
                <span v-else style="color: mediumseagreen">优惠 {{ scope.row.subtractMoney }} 元</span>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column label="发行信息" align="center">
          <template #default="scope">
            <el-row>
              <el-col :span="10"> 发行量： </el-col>
              <el-col :span="14">
                {{ scope.row.issueNumber }}
              </el-col>
            </el-row>
            <el-row style="margin-top: 10px">
              <el-col :span="10"> 剩余量： </el-col>
              <el-col :span="14">
                {{ scope.row.residueNumber }}
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column label="时间信息" align="center">
          <template #default="scope">
<!--            <el-row>-->
<!--              <el-col :span="10"> 领取时间： </el-col>-->
<!--              <el-col :span="14"> {{ parseTime(scope.row.discountsGetStartTime) }} 至 {{ parseTime(scope.row.discountsGetEndTime) }} </el-col>-->
<!--            </el-row>-->
            <el-row style="margin-top: 10px">
              <el-col :span="10"> 有效期： </el-col>
              <el-col :span="14">
                <span v-if="scope.row.discountsValidType == '1'"
                  >{{ parseTime(scope.row.validStartTime) }} 至 {{ parseTime(scope.row.validEndTime) }}</span
                >
                <span v-else>领取后{{ scope.row.validDays }}日内有效</span>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column label="限领信息" align="center">
          <template #default="scope">
            <span v-if="scope.row.getLimitType == '0'" style="color: green">无限制</span>
            <span v-else style="color: red">限领{{ scope.row.getLimitNumber }}次</span>
          </template>
        </el-table-column>
        <el-table-column label="状态" align="center">
          <template #default="scope">
            <el-tag v-if="scope.row.isDisabled == '1'" type="danger">已作废</el-tag>
            <el-tag v-else type="primary">正常</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="其他信息" align="center">
          <template #default="scope">
            <el-row>
              <el-col :span="12"> 券码类型： </el-col>
              <el-col :span="12">
                <dict-tag :options="discounts_cdk_type" :value="scope.row.discountsCdkType" />
              </el-col>
            </el-row>
            <el-row style="margin-top: 10px">
              <el-col :span="12"> 店铺展示： </el-col>
              <el-col :span="12">
                <dict-tag :options="sys_yes_no" :value="scope.row.isShopShow" />
              </el-col>
            </el-row>
            <el-row style="margin-top: 10px">
              <el-col :span="12"> 领券中心展示： </el-col>
              <el-col :span="12">
                <dict-tag :options="sys_yes_no" :value="scope.row.isGetCentreShow" />
              </el-col>
            </el-row>
            <el-row style="margin-top: 10px">
              <el-col :span="12"> 创建时间： </el-col>
              <el-col :span="12">
                {{ parseTime(scope.row.createTime) }}
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width" min-width="50px">
          <template #default="scope">
            <div>
              <el-button v-hasPermi="['shop:discountsInfo:log']" link type="primary" @click="openCdkLogDialog(scope.row)">领取记录</el-button>
            </div>
            <div style="margin-top: 10px">
              <el-button v-hasPermi="['shop:discountsInfo:add']" link type="success" @click="openCopyDialog(scope.row)">复制优惠券</el-button>
            </div>
            <div style="margin-top: 10px">
              <el-button v-hasPermi="['shop:discountsInfo:give']" link type="warning" @click="openGiveDialog(scope.row)">赠送</el-button>
            </div>
            <div style="margin-top: 10px">
              <el-button v-hasPermi="['shop:discountsInfo:disabled']" link type="danger" @click="openDisabledDiscountsDialog(scope.row)">作废</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" :total="total" @pagination="getList" />
    </el-card>
    <!-- 添加或修改优惠券信息对话框 -->
    <el-dialog v-model="dialog.visible" :title="dialog.title" width="65%" append-to-body>
      <el-form ref="discountsInfoFormRef" :model="form" :rules="rules" label-width="180px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="优惠券名称" prop="discountsName">
              <el-input v-model="form.discountsName" type="text" placeholder="请输入优惠券名称" maxlength="20" show-word-limit></el-input>
            </el-form-item>
          </el-col>
<!--          <el-col :span="12">-->
<!--            <el-form-item label="优惠券可领取时间" prop="discountsGetTimeList">-->
<!--              <el-date-picker-->
<!--                v-model="form.discountsGetTimeList"-->
<!--                type="datetimerange"-->
<!--                range-separator="至"-->
<!--                start-placeholder="可领取开始日期"-->
<!--                end-placeholder="可领取结束日期"-->
<!--                :format="formatTime"-->
<!--                :value-format="formatTime"-->
<!--                :default-time="defaultTime"-->
<!--              />-->
<!--            </el-form-item>-->
<!--          </el-col>-->
        </el-row>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="优惠券类型" prop="discountsType">
              <el-radio-group v-model="form.discountsType" @change="changeDiscountsType">
                <el-radio v-for="discountsType in discounts_type" :key="discountsType.value" :label="discountsType.value" border
                  >{{ discountsType.label }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col v-if="form.discountsType == '1'" :span="16" prop="fullAndSubtractRule">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="满" prop="fullUseMoney">
                  <el-input-number
                    v-model="form.fullUseMoney"
                    controls-position="right"
                    :min="1"
                    :precision="0"
                    placeholder="请输入满减限制金额"
                    style="width: 100%"
                    @blur="checkSubtractMoney"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="优惠" prop="subtractMoney">
                  <el-input-number
                    v-model="form.subtractMoney"
                    controls-position="right"
                    :min="1"
                    :max="form.fullUseMoney"
                    :precision="0"
                    placeholder="请输入优惠金额"
                    style="width: 100%"
                  />
                </el-form-item>
              </el-col>
            </el-row>
          </el-col>
          <el-col v-else-if="form.discountsType == '2'" :span="12" prop="subtractRule">
            <el-form-item label="优惠" prop="subtractMoney">
              <el-input-number
                v-model="form.subtractMoney"
                controls-position="right"
                :min="1"
                :precision="0"
                placeholder="请输入优惠金额"
                style="width: 50%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="优惠券发行数量" prop="issueNumber">
              <el-tooltip
                class="box-item"
                effect="dark"
                :content="'单次最大发行数量' + discountsOnceMaxIssueNumber + '张'"
                placement="top-start">
                <el-input-number
                  v-model="form.issueNumber"
                  controls-position="right"
                  :min="1"
                  :max="discountsOnceMaxIssueNumber"
                  :precision="0" />
              </el-tooltip>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="券码类型" prop="discountsCdkType">
              <el-radio-group v-model="form.discountsCdkType">
                <el-tooltip
                  class="box-item"
                  effect="dark"
                  content="该批次下每张优惠券的券码都不一样,例如发行数量是10,则十张优惠券每张的券码均不相同"
                  placement="top-start">
                  <el-radio label="1" border>唯一券码</el-radio>
                </el-tooltip>
                <el-tooltip
                  class="box-item"
                  effect="dark"
                  content="该批次下每张优惠券的券码都一样,例如发行数量是10,则十张优惠券券码均相同,常用于使用同一券码为多名用户发放优惠券"
                  placement="top-start">
                  <el-radio label="2" border>共用券码</el-radio>
                </el-tooltip>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="优惠券有效期类型" prop="discountsValidType">
              <el-radio-group v-model="form.discountsValidType">
                <el-radio v-for="(validType, index) in discounts_valid_type" :key="index" :value="validType.value">{{ validType.label }}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col v-if="form.discountsValidType == '1'" :span="16">
            <el-form-item prop="validTimeList">
              <el-date-picker
                v-model="form.validTimeList"
                type="datetimerange"
                range-separator="至"
                start-placeholder="有效期开始日期"
                end-placeholder="有效期结束日期"
                :format="formatTime"
                :value-format="formatTime"
                :default-time="defaultTime"
              />
            </el-form-item>
          </el-col>
          <el-col v-if="form.discountsValidType == '2'" :span="16">
            <el-form-item prop="validTodayDays">
              <span>
                领券后<el-input-number
                  v-model="form.validDays"
                  controls-position="right"
                  :min="1"
                  :precision="0"
                  style="margin-left: 10px; margin-right: 10px; width: 60%"
                  placeholder="请输入天数"
                ></el-input-number
                >日内可用
              </span>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="是否限领" prop="getLimitType">
              <el-radio-group v-model="form.getLimitType" @change="changeGetLimitType">
                <el-radio v-for="(dict, index) in sys_yes_no" :key="index" :value="dict.value">{{ dict.label }}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col v-if="form.getLimitType == '1'" :span="16">
            <el-form-item label="限领几次" prop="getLimitNumber">
              <el-input-number
                v-model="form.getLimitNumber"
                controls-position="right"
                placeholder="请输入限领几次"
                :min="1"
                :max="form.issueNumber"
                :precision="0"
                style="width: 30%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="店铺展示该优惠券" prop="isShopShow">
              <el-radio-group v-model="form.isShopShow">
                <el-radio v-for="(dict, index) in sys_yes_no" :key="index" :value="dict.value">{{ dict.label }}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="领券中心展示该优惠券" prop="isGetCentreShow">
              <el-radio-group v-model="form.isGetCentreShow">
                <el-radio v-for="(dict, index) in sys_yes_no" :key="index" :value="dict.value">{{ dict.label }}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="作用范围" prop="goodsScopeType">
              <el-radio-group v-model="form.goodsScopeType">
                <el-radio value="2">店铺全部商品</el-radio>
                <el-radio value="3">店铺指定商品</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="16">
            <el-form-item label="指定商品" prop="collageId" v-if="form.goodsScopeType == '3'">
              <el-select v-model="form.collageId" placeholder="请选择">
                <el-option
                  v-for="collage in shopStartCollageList"
                  :key="collage.id"
                  :label="collage.collageName"
                  :value="collage.id"
                  style="height: 80px">
                  <image-preview style="float: left" :src="collage.imagePath" width="80px" height="100px"/>
                  <span style="float: right; font-size: 13px">{{ collage.collageName }}【{{collage.collageCode}}】</span>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!--  优惠券作废 -->
    <el-dialog v-model="disabledDialog.visible" :title="disabledDialog.title" width="30%" append-to-body>
      <el-form ref="disabledFormRef" :model="disabledForm" :rules="disabledRules" label-width="180px">
        <el-form-item label="作废范围" prop="disabledCodeStatusList">
          <el-checkbox-group v-model="disabledForm.disabledCodeStatusList">
            <el-checkbox label="未领取作废" value="0" />
            <el-checkbox label="已领取未使用作废" value="1" />
          </el-checkbox-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="danger" @click="submitDisabled">作 废</el-button>
        </div>
      </template>
    </el-dialog>

    <!--  优惠券领取记录 -->
    <el-dialog v-model="cdkLogDialog.visible" :title="cdkLogDialog.title" width="85%" v-if="cdkLogDialog.visible" append-to-body destroy-on-close>
      <DiscountsCdkLog :discounts-id="discountsId" />
    </el-dialog>

    <!--  优惠券赠送 -->
    <el-dialog v-model="discountsGiveDialog.visible" :title="discountsGiveDialog.title" width="35%" v-if="discountsGiveDialog.visible" append-to-body destroy-on-close>
      <el-form ref="giveFormRef" :model="giveForm" :rules="giveRules" label-width="auto">
        <el-form-item label="赠送人" prop="queryData">
          <el-input
            v-model="giveForm.queryData"
            placeholder="请输入赠送人"
            class="input-with-select">
            <template #prepend>
              <el-select v-model="giveForm.queryType" placeholder="类型" style="width: 130px">
                <el-option label="手机号" value="phone" />
                <el-option label="玩家号" value="inviteCode" />
              </el-select>
            </template>
            <template #append>
              <el-button :disabled="!giveForm.queryData" :icon="Search" @click="queryUserInfo"/>
            </template>
          </el-input>
        </el-form-item>
        <el-card style="margin-top: 10px; margin-bottom: 10px" v-if="giveForm.appUserVo.phone">
          <el-descriptions :column="2" border>
            <el-descriptions-item label="用户头像">
              <image-preview v-if="giveForm.appUserVo.headPortrait" :src="giveForm.appUserVo.headPortrait" width="100px" height="100px"/>
            </el-descriptions-item>
            <el-descriptions-item label="用户昵称">{{giveForm.appUserVo.nickName}}</el-descriptions-item>
            <el-descriptions-item label="用户手机号">{{giveForm.appUserVo.phone}}</el-descriptions-item>
            <el-descriptions-item label="用户玩家号">{{giveForm.appUserVo.inviteCode}}</el-descriptions-item>
          </el-descriptions>
        </el-card>
        <el-form-item label="赠送张数" prop="giveCount">
          <el-input-number v-model="giveForm.giveCount" :min="1" :max="form.residueNumber" :step="0" style="width: 100%" />
        </el-form-item>
      </el-form>
      <div>
        <span style="color: red"><el-icon style="margin-right: 10px"><Warning /></el-icon>优惠券剩余数量：{{form.residueNumber}} 张</span>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-popconfirm
            confirm-button-text="确定"
            cancel-button-text="取消"
            :icon="InfoFilled"
            icon-color="#626AEF"
            title="确定要向该用户赠送优惠券码?"
            @confirm="submitGiveDiscounts">
            <template #reference>
              <el-button :loading="buttonLoading" type="success">赠 送</el-button>
            </template>
          </el-popconfirm>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="DiscountsInfo" lang="ts">
import {
  listDiscountsInfo,
  addDiscountsInfo,
  discountsInfoDisabled,
  queryShopStartCollageList,
  getDiscountsInfoById,
  giveDiscounts
} from '@/api/system/discountsInfo';
import { queryUserInfoByType } from '@/api/system/appUser';
import { DiscountsInfoVO, DiscountsInfoQuery, DiscountsInfoForm } from '@/api/system/discountsInfo/types';
import { DiscountsCdkLogForm } from '@/api/system/discountsCdkLog/types';
import { CardCollageVO } from '@/api/system/cardCollage/types';

import DiscountsCdkLog from '@/views/system/discountsCdkLog/index.vue';
import { InfoFilled, Search } from '@element-plus/icons-vue';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { discounts_type, discounts_valid_type, sys_yes_no, discounts_cdk_type, discounts_issue_type, goods_scope_type } = toRefs<any>(
  proxy?.useDict('discounts_type', 'discounts_valid_type', 'sys_yes_no', 'discounts_cdk_type', 'discounts_issue_type', 'goods_scope_type')
);
const discountsOnceMaxIssueNumber = ref<number>(undefined);

const discountsInfoList = ref<DiscountsInfoVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const discountsId = ref<number>(undefined);

const queryFormRef = ref<ElFormInstance>();
const discountsInfoFormRef = ref<ElFormInstance>();
const disabledFormRef = ref<ElFormInstance>();
const copyFormRef = ref<ElFormInstance>();
const giveFormRef = ref<ElFormInstance>();

const shopStartCollageList = ref<CardCollageVO[]>([]);

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const cdkLogDialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const disabledDialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const discountsGiveDialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const defaultTime: [Date, Date] = [new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 2, 1, 23, 59, 59)];

const formatTime: string = 'YYYY-MM-DD HH:mm:ss';

const initFormData: DiscountsInfoForm = {
  discountsId: undefined,
  discountsIssueType: undefined,
  shopId: undefined,
  collageId: undefined,
  discountsCode: undefined,
  discountsName: undefined,
  discountsType: undefined,
  discountsCdkType: undefined,
  fullUseMoney: undefined,
  subtractMoney: undefined,
  issueNumber: undefined,
  residueNumber: undefined,
  discountsValidType: undefined,
  validStartTime: undefined,
  validEndTime: undefined,
  validDays: undefined,
  getLimitType: undefined,
  getLimitNumber: undefined,
  goodsScopeType: undefined,
  discountsGetStartTime: undefined,
  discountsGetEndTime: undefined,
  isDisabled: undefined,
  isShopShow: undefined,
  isGetCentreShow: undefined,
  showOrder: undefined,
  deleteFlag: undefined,
  validTimeList: [],
  discountsGetTimeList: []
};
const data = reactive<PageData<DiscountsInfoForm, DiscountsInfoQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    discountsIssueType: '2',
    shopId: undefined,
    collageId: undefined,
    discountsCode: undefined,
    discountsName: undefined,
    discountsType: undefined,
    discountsCdkType: undefined,
    fullUseMoney: undefined,
    subtractMoney: undefined,
    issueNumber: undefined,
    residueNumber: undefined,
    discountsValidType: undefined,
    validStartTime: undefined,
    validEndTime: undefined,
    validDays: undefined,
    getLimitType: undefined,
    getLimitNumber: undefined,
    goodsScopeType: undefined,
    discountsGetStartTime: undefined,
    discountsGetEndTime: undefined,
    isDisabled: undefined,
    isShopShow: undefined,
    isGetCentreShow: undefined,
    showOrder: undefined,
    deleteFlag: undefined,
    params: {},
    queryCreateTime: 7,
  },
  rules: {
    discountsId: [{ required: true, message: '优惠券ID不能为空', trigger: 'blur' }],
    discountsIssueType: [{ required: true, message: '优惠券发行方不能为空', trigger: 'change' }],
    shopId: [{ required: true, message: '优惠券发行店铺ID不能为空', trigger: 'blur' }],
    collageId: [{ required: true, message: '指定商品不能为空', trigger: 'blur' }],
    discountsCode: [{ required: true, message: '优惠券编号不能为空', trigger: 'blur' }],
    discountsName: [{ required: true, message: '优惠券名称不能为空', trigger: 'blur' }],
    discountsType: [{ required: true, message: '优惠券类型不能为空', trigger: 'change' }],
    discountsCdkType: [{ required: true, message: '优惠券CDK类型不能为空', trigger: 'change' }],
    fullUseMoney: [{ required: true, message: '满多少可用不能为空', trigger: 'blur' }],
    subtractMoney: [{ required: true, message: '减多少钱不能为空', trigger: 'blur' }],
    issueNumber: [{ required: true, message: '发行数量不能为空', trigger: 'blur' }],
    residueNumber: [{ required: true, message: '剩余数量不能为空', trigger: 'blur' }],
    discountsValidType: [{ required: true, message: '优惠券有效期类型不能为空', trigger: 'change' }],
    validTimeList: [{ required: true, message: '有效期不能为空', trigger: 'blur' }],
    validDays: [{ required: true, message: '几日内有效不能为空', trigger: 'blur' }],
    getLimitType: [{ required: true, message: '领取限制类型不能为空', trigger: 'change' }],
    getLimitNumber: [{ required: true, message: '限领几次不能为空', trigger: 'blur' }],
    goodsScopeType: [{ required: true, message: '商品范围不能为空', trigger: 'change' }],
    // discountsGetTimeList: [{ required: true, message: '可领取时间不能为空', trigger: 'blur' }],
    isShopShow: [{ required: true, message: '是否前端展示不能为空', trigger: 'blur' }],
    isGetCentreShow: [{ required: true, message: '领券中心是否展示不能为空', trigger: 'blur' }],
  }
});

const initDisabledFormData: DiscountsCdkLogForm = {
  discountsId: undefined,
  disabledCodeStatusList: []
};

const disabledData = reactive({
  disabledForm: { ...initDisabledFormData },
  disabledRules: {
    discountsId: [{ required: true, message: '优惠券ID不能为空', trigger: 'blur' }],
    disabledCodeStatusList: [{ required: true, message: '作废范围不能为空', trigger: 'change' }]
  }
});

const copyData = reactive({
  copyForm: {
    discountsId: undefined,
    discountsGetTimeList: [],
    validTimeList: [],
  },
  copyRules: {
    discountsGetTimeList: [{ required: true, message: '可领取时间不能为空', trigger: 'blur' }],
    validTimeList: [{ required: true, message: '有效期不能为空', trigger: 'blur' }],
  },
});

const giveData = reactive({
  giveForm: {
    discountsId: undefined,
    queryType: 'phone',
    queryData: undefined,
    giveCount: undefined,
    appUserVo: {
      headPortrait: undefined,
      nickName: undefined,
      phone: undefined,
      inviteCode: undefined
    },
  },
  giveRules: {

  },
});

const { queryParams, form, rules } = toRefs(data);

const { disabledForm, disabledRules } = toRefs(disabledData);

const { copyForm, copyRules } = toRefs(copyData);

const { giveForm, giveRules } = toRefs(giveData);

/** 查询优惠券信息列表 */
const getList = async () => {
  loading.value = true;
  const res = await listDiscountsInfo(queryParams.value);
  discountsInfoList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
};

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  discountsInfoFormRef.value?.resetFields();
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = '添加优惠券信息';
  queryShopStartCollageListData();
};

/** 提交按钮 */
const submitForm = () => {
  discountsInfoFormRef.value?.validate( (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      addDiscountsInfo(form.value).then(() => {
        proxy?.$modal.msgSuccess('操作成功');
        dialog.visible = false;
        setTimeout(() => {
          getList();
        }, 500);
      }).finally(() => (buttonLoading.value = false));
    }
  });
};

/**
 * 切换优惠券类型
 */
const changeDiscountsType = () => {
  form.value.fullUseMoney = undefined;
  form.value.subtractMoney = undefined;
};

/**
 * 切换限购类型
 */
const changeGetLimitType = () => {
  form.value.getLimitNumber = undefined;
}

/**
 * 校验满减限制金额不能大于满减金额
 */
const checkSubtractMoney = () => {
  if (form.value.fullUseMoney && form.value.subtractMoney) {
    if (form.value.subtractMoney >= form.value.fullUseMoney) {
      form.value.subtractMoney = undefined;
    }
  }
};

/**
 * 打开领取记录对话框
 */
const openCdkLogDialog = (row?: DiscountsInfoVO) => {
  cdkLogDialog.visible = true;
  cdkLogDialog.title = '【' + row.discountsName + '】优惠券领取记录';
  discountsId.value = row.discountsId;
};

/**
 * 打开优惠券作废对话框
 */
const openDisabledDiscountsDialog = (row?: DiscountsInfoVO) => {
  disabledDialog.visible = true;
  disabledDialog.title = '【' + row.discountsName + '】优惠券作废';
  disabledForm.value.discountsId = row.discountsId;
};

/**
 * 关闭优惠券作废对话框
 */
const closeDisabledDiscountsDialog = () => {
  disabledDialog.visible = false;
}

/**
 * 优惠券作废
 */
const submitDisabled = () => {
  disabledFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      await discountsInfoDisabled(disabledForm.value).finally(() => (buttonLoading.value = false));
      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
      await getList();
      closeDisabledDiscountsDialog();
    }
  });
};

/**
 * 查询店铺正在进行中的拼团
 */
const queryShopStartCollageListData = async () => {
  await queryShopStartCollageList().then(res => {
    shopStartCollageList.value = res.data;
  });
};

/**
 * 打开优惠券复制对话框
 */
const openCopyDialog = async (row?: DiscountsInfoVO) => {
  dialog.visible = true;
  dialog.title = '复制优惠券';
  await queryDiscountsInfoById(row);
  await queryShopStartCollageListData();

  form.value.discountsGetTimeList = [];
  form.value.isDisabled = undefined;
  var flag = false;
  for(var i=0; i<shopStartCollageList.value.length; i++){
    const cardCollageVO = shopStartCollageList.value[i];
    if(cardCollageVO.id == form.value.collageId){
      flag = true;
    }
  }
  if(!flag){
    form.value.collageId = undefined;
  }
}

/**
 * 查询优惠券详情
 */
const queryDiscountsInfoById = async (row?: DiscountsInfoVO) => {
  const res = await getDiscountsInfoById(row.discountsId)
  form.value = res.data;
}

/**
 * 打开优惠券赠送对话框
 */
const openGiveDialog = (row?: DiscountsInfoVO) => {
  giveReset();
  discountsGiveDialog.visible = true;
  discountsGiveDialog.title = '【' + row.discountsName + '】优惠券赠送';
  giveForm.value.discountsId = row.discountsId;
  queryDiscountsInfoById(row);
}

/**
 * 根据类型查询用户信息
 */
const queryUserInfo = async () => {
  const res = await queryUserInfoByType(giveForm.value.queryType, giveForm.value.queryData);
  giveForm.value.appUserVo = res.data;
}

/**
 * 赠送优惠券
 */
const submitGiveDiscounts = async () => {
  buttonLoading.value = true;
  const res = await giveDiscounts(giveForm.value).finally(() =>  buttonLoading.value = false);
  proxy?.$modal.msgSuccess('优惠券赠送成功');
  discountsGiveDialog.visible = false;
  await getList();
}

/**
 * 赠送优惠券表单重置
 */
const giveReset = () => {
  giveForm.value = {
    discountsId: undefined,
      queryType: 'phone',
      queryData: undefined,
      giveCount: undefined,
      appUserVo: {
      headPortrait: undefined,
        nickName: undefined,
        phone: undefined,
        inviteCode: undefined
    },
  };
  giveFormRef.value?.resetFields();
};

onMounted(() => {
  getList();
  proxy?.getConfigKey('discounts_once_max_issue_number').then((response) => {
    if(response.data){
      discountsOnceMaxIssueNumber.value = Number(response.data);
    }
  });
});
</script>
